import axios from 'axios'
import useApp from '@/store/app'
import jsonBig from 'json-bigint'
import { ElMessage } from 'element-plus'
import { removeToken } from '@/utils/auth'

const instance = axios.create({
  baseURL: process.env.VUE_APP_API_URL,
  timeout: 60000,
  transformResponse: (data) => {
    try {
      return jsonBig({ storeAsString: true }).parse(data)
    } catch (e) {
      return data
    }
  },
})

instance.interceptors.request.use(
  (config) => {
    const { isToken } = config.headers || {}
    if (isToken !== false) {
      const appStore = useApp()
      config.headers['Authorization'] = 'Bearer ' + appStore.token
    }
    config.headers['content-language'] = 'zh-cn'
    // 灰度测试
    if (process.env.VUE_APP_DEV_GRAY) {
      config.headers['dev-gray'] = process.env.VUE_APP_DEV_GRAY
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  (response) => {
    const { data, status } = response
    if (status === 200) {
      if (data.code === 401) {
        const router = useRouter()
        sessionStorage.clear()
        localStorage.clear()
        removeToken()
        router.push('/login')
      }
      if (data.code === 403) {
        ElMessage.warning('暂无权限')
      }
      return data
    }
  },
  (error) => {
    return Promise.reject(error)
  }
)

export default instance
